package com.manager.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/*
 * 字符编码工具类
 */
public class CharUtil {
	public static final String GBK = "GBK";

	public static final String GB2312 = "GB2312";

	public static final String UTF_8 = "UTF-8";

	public static final String UTF_16 = "UTF-16";

	public static final String UTF_16BE = "UTF-16BE";

	public static final String UTF_16LE = "UTF-16LE";

	public static final String US_ASCII = "US-ASCII";

	public static final String ISO_8859_1 = "ISO-8859-1";// ISO-LATIN-1

	public static String toASCII(String str) {
		return changeCharset(str, US_ASCII);
	}

	public static String toISO_8859_1(String str) {
		return changeCharset(str, ISO_8859_1);
	}

	public static String toUTF_8(String str) {
		return changeCharset(str, UTF_8);
	}

	public static String toUTF_16BE(String str) {
		return changeCharset(str, UTF_16BE);
	}

	public static String toUTF_16LE(String str) {
		return changeCharset(str, UTF_16LE);
	}

	public static String toUTF_16(String str) {
		return changeCharset(str, UTF_16);
	}

	public static String toGBK(String str) {
		return changeCharset(str, GBK);
	}
	
	public static String toGB2312(String str) {
		return changeCharset(str, GB2312);
	}
	
	/*
	 * 将字符串用unicode编码
	 * 注：你也可以使用native2ascii，在%JAVA_HOME%/bin
	 * 使用方法：
	 * (1)native2ascii 测试
	   \u6d4b\u8bd5
	   (2)native2ascii -reverse \u6d4b\u8bd5
	    测试
	 */
	public static String toUnicode(String str) {
		char[] utfBytes = str.toCharArray();
		String unicodeBytes = "";
		for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
			String hexB = Integer.toHexString(utfBytes[byteIndex]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "\\u" + hexB;
		}
		return unicodeBytes;
	}
	
	/*
	 * 字符串编码转换的实现方法 @param str 待转换编码的字符串 @param newCharset 目标编码 @return @throws
	 */
	public static String changeCharset(String str, String newCharset) {
		try {
			return new String(str.getBytes(), newCharset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 字符串编码转换的实现方法 @param str 待转换编码的字符串 @param oldCharset 原编码 @param newCharset
	 * 目标编码
	 */
	public static String changeCharset(String str, String oldCharset, String newCharset) {
		try {
			return new String(str.getBytes(oldCharset), newCharset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/*
	 * URLEncoder
	 * str[0] 将要编码的字符串
	 * str[1] 编码方式
	 */
	public static String encodeURL(String... str ){
		String encode = null;
		try {
			if(str.length == 1){
				encode = CharUtil.UTF_8;
			}else{
				encode = str[1];
			}
			return URLEncoder.encode(str[0], encode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		
	}
}
